<template>
  <view class="role-list">
    <!-- 错误提示 -->
    <view v-if="error" class="error-message">{{ error }}</view>

    <!-- 工具栏 -->
    <view class="toolbar">
      <button type="primary" @click="handleAdd">新增角色</button>
      <text class="role-count" v-if="roles.length > 0">共 {{ roles.length }} 个角色</text>
    </view>

    <!-- 角色列表 -->
    <uni-table :loading="loading" border stripe emptyText="暂无角色数据">
      <uni-tr>
        <uni-th align="center">角色名称</uni-th>
        <uni-th align="center">角色编码</uni-th>
        <uni-th align="center">描述</uni-th>
        <uni-th align="center">创建时间</uni-th>
        <uni-th align="center">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="role in roles" :key="role.id">
        <uni-td align="center">{{ role.roleName }}</uni-td>
        <uni-td align="center">{{ role.roleCode }}</uni-td>
        <uni-td align="center">{{ role.description }}</uni-td>
        <uni-td align="center">{{ formatDateTimeArray(role.createTime) }}</uni-td>
        <uni-td align="center">
          <view class="operation">
            <button size="mini" type="primary" @click="handleEdit(role)">编辑</button>
            <button size="mini" type="warn" @click="handleDelete(role)">删除</button>
          </view>
        </uni-td>
      </uni-tr>
    </uni-table>

    <!-- 自定义弹窗：新增/编辑 -->
    <view v-if="showFormPopup" class="custom-popup-mask" @click.self="closeFormPopup">
      <view class="custom-popup-dialog">
        <view class="popup-title">{{ formData.id ? '编辑角色' : '新增角色' }}</view>
        <view class="form-item">
          <text class="label">角色名称</text>
          <input v-model="formData.roleName" class="popup-input" placeholder="请输入角色名称" />
        </view>
        <view class="form-item">
          <text class="label">角色编码</text>
          <input v-model="formData.roleCode" class="popup-input" placeholder="请输入角色编码（如 ROLE_ADMIN）" />
        </view>
        <view class="form-item">
          <text class="label">描述</text>
          <textarea v-model="formData.description" class="popup-textarea" placeholder="请输入角色描述" />
        </view>
        <view class="form-actions">
          <button type="primary" @click="submitForm">{{ formData.id ? '保存修改' : '创建角色' }}</button>
          <button @click="closeFormPopup">取消</button>
        </view>
      </view>
    </view>

    <!-- 自定义弹窗：删除确认 -->
    <view v-if="showDeletePopup" class="custom-popup-mask" @click.self="closeConfirmPopup">
      <view class="custom-popup-dialog">
        <view class="popup-title">删除角色</view>
        <view class="popup-content">确定要删除该角色吗？</view>
        <view class="form-actions">
          <button type="warn" @click="confirmDelete">确定</button>
          <button @click="closeConfirmPopup">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      roles: [],
      formTitle: '新增角色',
      formData: {
        id: null,
        roleName: '',
        roleCode: '',
        description: ''
      },
      deleteId: null,
      error: null,
      showFormPopup: false,
      showDeletePopup: false
    }
  },
  mounted() {
    this.loadRoles()
  },
  methods: {
    formatDateTimeArray(timeArray) {
      if (!timeArray || !Array.isArray(timeArray) || timeArray.length < 6) return '-';
      const [year, month, day, hour, minute, second] = timeArray;
      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
    },
    // 加载角色列表
    async loadRoles() {
      try {
        this.loading = true
        this.error = null
        if (!this.$api || !this.$api.role) {
          throw new Error('角色管理API未正确配置')
        }
        const response = await this.$api.role.getAllRoles()
        if (response && response.data) {
          this.roles = response.data
        } else {
          throw new Error('返回数据格式不正确')
        }
      } catch (error) {
        this.error = `加载失败: ${error.message || '未知错误'}`
        uni.showToast({
          title: '加载角色列表失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
      }
    },
    // 处理新增角色
    handleAdd() {
      this.formTitle = '新增角色'
      this.formData = {
        id: null,
        roleName: '',
        roleCode: '',
        description: ''
      }
      this.showFormPopup = true
    },
    // 处理编辑角色
    handleEdit(role) {
      this.formTitle = '编辑角色'
      this.formData = {
        id: role.id,
        roleName: role.roleName,
        roleCode: role.roleCode,
        description: role.description
      }
      this.showFormPopup = true
    },
    // 表单提交校验
    async submitForm() {
      if (!this.formData.roleName || !this.formData.roleName.trim()) {
        uni.showToast({ title: '角色名称不能为空', icon: 'none' })
        return
      }
      if (!this.formData.roleCode || !this.formData.roleCode.trim()) {
        uni.showToast({ title: '角色编码不能为空', icon: 'none' })
        return
      }
      try {
        if (this.formData.id) {
          await this.$api.role.updateRole(this.formData)
        } else {
          await this.$api.role.createRole(this.formData)
        }
        uni.showToast({
          title: this.formData.id ? '更新成功' : '创建成功',
          icon: 'success'
        })
        this.closeFormPopup()
        this.loadRoles()
      } catch (error) {
        uni.showToast({
          title: this.formData.id ? '更新失败' : '创建失败',
          icon: 'error'
        })
      }
    },
    // 处理删除角色
    handleDelete(role) {
      this.deleteId = role.id
      this.showDeletePopup = true
    },
    // 确认删除
    async confirmDelete() {
      try {
        await this.$api.role.deleteRole(this.deleteId)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.loadRoles()
      } catch (error) {
        uni.showToast({
          title: '删除失败',
          icon: 'error'
        })
      }
      this.closeConfirmPopup()
    },
    // 关闭表单弹窗
    closeFormPopup() {
      this.showFormPopup = false
    },
    // 关闭确认弹窗
    closeConfirmPopup() {
      this.deleteId = null
      this.showDeletePopup = false
    }
  }
}
</script>

<style>
.role-list {
  padding: 20px;
}
.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.role-count {
  color: #666;
  font-size: 14px;
}
.operation {
  display: flex;
  justify-content: center;
  gap: 10px;
}
.operation button {
  margin: 0;
}
.error-message {
  padding: 10px;
  margin-bottom: 10px;
  background-color: #fef0f0;
  color: #f56c6c;
  border-radius: 4px;
}

/* 自定义弹窗样式 */
.custom-popup-mask {
  position: fixed;
  z-index: 9999;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-popup-dialog {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 8px 32px rgba(63,81,181,0.18);
  min-width: 320px;
  max-width: 90vw;
  padding: 28px 24px 18px 24px;
  animation: popup-fade-in 0.18s;
}
@keyframes popup-fade-in {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}
.popup-title {
  font-size: 20px;
  font-weight: 600;
  color: #3f51b5;
  margin-bottom: 18px;
  text-align: center;
}
.popup-content {
  font-size: 16px;
  color: #333;
  margin-bottom: 18px;
  text-align: center;
}
.form-item {
  margin-bottom: 18px;
}
.label {
  display: block;
  margin-bottom: 6px;
  color: #333;
  font-size: 15px;
  font-weight: 500;
}
.popup-input {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #e3e7f7;
  border-radius: 6px;
  font-size: 15px;
  background: #f8faff;
  outline: none;
  transition: border 0.2s;
}
.popup-input:focus {
  border-color: #3f51b5;
}
.popup-textarea {
  width: 100%;
  min-height: 60px;
  padding: 8px 10px;
  border: 1px solid #e3e7f7;
  border-radius: 6px;
  font-size: 15px;
  background: #f8faff;
  outline: none;
  resize: vertical;
  transition: border 0.2s;
}
.popup-textarea:focus {
  border-color: #3f51b5;
}
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 10px;
}
.form-actions button[type="primary"] {
  background: #3f51b5;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 7px 18px;
  font-size: 15px;
  font-weight: 500;
  transition: background 0.2s;
}
.form-actions button[type="primary"]:active {
  background: #283593;
}
.form-actions button[type="warn"] {
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 7px 18px;
  font-size: 15px;
  font-weight: 500;
  transition: background 0.2s;
}
.form-actions button[type="warn"]:active {
  background: #d32f2f;
}
.form-actions button {
  background: #f5f7fa;
  color: #3f51b5;
  border: none;
  border-radius: 6px;
  padding: 7px 18px;
  font-size: 15px;
  font-weight: 500;
  transition: background 0.2s;
}
.form-actions button:active {
  background: #e3e7f7;
}
</style> 